<template>
	<view class="page">
		<scroll-view class="scroll-view" scroll-y scroll-with-animation :scroll-top="top"
			:style="{ height: scrollViewHeight + 'px' }" @scroll="onScroll" :scroll-into-view="scrollIntoView">
			<view style="padding: 30rpx 30rpx 20rpx;">
				<view v-for="(item, index) in list" :key="index" :id="'msg-' + index">
					<!-- 添加时间显示 -->
					<view class="time-box">
						<text class="time-text">{{ item.time }}</text>
					</view>

					<view class="message" :class="[item.userType]">
						<image :src="item.avatar" v-if="item.userType === 'friend'" class="avatar" mode="widthFix"></image>
						<view class="content" v-if="item.messageType === 'image'">
							<image :src="item.content" mode="widthFix"></image>
						</view>
						<view class="content" v-else>
							{{ item.content }}
						</view>
						<image :src="item.avatar" v-if="item.userType === 'self'" class="avatar" mode="widthFix"></image>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="tool" :style="{ bottom: keyboardHeight + 'px' }">
			<input type="text" v-model="content" class="input" :adjust-position="false" :hold-keyboard="true"
				@focus="onInputFocus" @blur="onInputBlur" @confirm="send" />
			<image src="../../static/img/send.png" mode="widthFix" class="thumb" @click="send"></image>
		</view>
	</view>
</template>

<script>
import messageManager from '@/common/js/messageManager.js'
import newsApi from "@/common/api/news.js"
export default {
	data() {
		return {
			content: '',
			list: [],
			top: 0,
			keyboardHeight: 0,
			scrollViewHeight: 0,
			scrollIntoView: '',
			systemInfo: null,
			chatUser: null,
			chatUserId: null,
			mineId: '',
			mineName: '',
			mineAvatar: '',
			sign: '',
			status: '',
			userId: '',
			username: '',
			useravatar: ''
		};
	},
	onLoad(options) {
		uni.$on('newMessage', this.handleNewMessage)
		const user = uni.getStorageSync('user') || {};
		console.log('options-wy', options, user);
		this.mineId = options.mineId
		this.mineName = options.mineName
		this.mineAvatar = options.mineAvatar
		this.sign = options.sign
		this.status = options.status
		this.userId = options.userId
		messageManager.setUserId(this.userId);
		this.username = options.name
		this.useravatar = options.avatar
		this.history(options.userId)
		// 获取聊天对象信息
		this.chatUser = {
			name: options.name || '客服',
			avatar: options.avatar || 'https://oa.apiwww.cn/storage/202506/n9ao1_6f049f9e22f479df9c7dd679e3511e7c.png'
		}
		this.chatUserId = options.userId || '1'

		this._friendAvatar = this.chatUser.avatar
		this._selfAvatar = user.avatar || 'https://kaoshi.apiwww.cn/uploads/20250619/12c324be20bb2c209decc9ff3fd44718.jpeg'


		// 获取系统信息
		this.getSystemInfo()

		// 监听键盘高度变化
		uni.onKeyboardHeightChange((res) => {
			this.keyboardHeight = res.height
			this.updateScrollViewHeight()
		})

		// 设置消息监听
		this.setupMessageListener()

		// 通知进入聊天页面
		uni.$emit('enterChat', this.chatUserId)
	},
	onShow() {
		// 页面显示时通知进入聊天
		uni.$emit('enterChat', this.chatUserId)
	},
	onReady() {
		this.updateScrollViewHeight()
		this.scrollToBottom()
	},
	onUnload() {
		// 页面卸载时通知离开聊天
		uni.$emit('leaveChat')
		// 移除消息监听
		messageManager.removeMessageListener(this.chatUserId, this.handleNewMessage)
	},
	beforeDestroy() {
     uni.$off('newMessage', this.handleNewMessage)
   },
	methods: {
		// 历史消息
		history(id) {
			const data = {
				targetid: id,
				client_id: messageManager.getClientId()
			}
			newsApi.messageHistory(this, data).then((res) => {
				console.log('res.data', res.data);
				const data = res.data.list.reverse();
				data.forEach(item => {
					this.list.push({
						content: item.content[0].data,
						userType: item.id == this.mineId ? 'self' : 'friend',
						avatar: item.avatar != '' ? item.avatar : this._selfAvatar,
						time: item.timestamp
					})
				});
				this.scrollToBottom()
			})
		},
		// 设置消息监听
		setupMessageListener() {
			// 添加特定用户的消息监听器
			messageManager.addMessageListener(this.chatUserId, this.handleNewMessage)
		},

		// 处理新消息
		handleNewMessage(message) {
			console.log('message-wy',message);
			this.list.push({
				content: message.content,
				userType: 'friend',
				avatar: this._friendAvatar,
				time: this.formatTime(new Date(message.timestamp))
			})
			this.scrollToBottom()
		},

		formatTime(date = new Date(), format = 'YYYY-MM-DD HH:MM') {
			const year = date.getFullYear();
			const month = (date.getMonth() + 1).toString().padStart(2, '0');
			const day = date.getDate().toString().padStart(2, '0');
			const hours = date.getHours().toString().padStart(2, '0');
			const minutes = date.getMinutes().toString().padStart(2, '0');

			return format
				.replace('YYYY', year)
				.replace('MM', month)
				.replace('DD', day)
				.replace('HH', hours)
				.replace('MM', minutes);
		},

		// 获取系统信息
		getSystemInfo() {
			uni.getSystemInfo({
				success: (res) => {
					this.systemInfo = res
					this.updateScrollViewHeight()
				}
			})
		},

		// 更新滚动区域高度
		updateScrollViewHeight() {
			if (!this.systemInfo) return

			const windowHeight = this.systemInfo.windowHeight
			const toolHeight = 120 // 输入框区域高度
			const safeAreaBottom = this.systemInfo.safeAreaInsets?.bottom || 0

			// 计算滚动区域高度 = 窗口高度 - 输入框高度 - 键盘高度 - 安全区域
			this.scrollViewHeight = windowHeight - toolHeight - this.keyboardHeight - safeAreaBottom
		},

		// 输入框获得焦点
		onInputFocus(e) {
			// 延迟滚动到底部，确保键盘完全弹出
			setTimeout(() => {
				this.scrollToBottom()
			}, 300)
		},

		// 输入框失去焦点
		onInputBlur(e) {
			// 键盘收起时的处理
		},

		// 滚动事件
		onScroll(e) {
			// 可以在这里处理滚动事件
		},

		send() {
			if (!this.content.trim()) return

			// 先本地追加
			this.list.push({
				content: this.content,
				userType: 'self',
				avatar: this._selfAvatar,
				time: this.formatTime()
			})
			const message = {
				data: {
					mine: {
						id: this.mineId,
						username: this.mineName,
						avatar: this.mineAvatar,
						mine: true,
						content: this.content
					},
					to: {
						id: this.userId,
						username: this.username,
						avatar: this.useravatar,
						sign: this.sign,
						status: this.status,
						name: this.username,
						type: "friend"
					}
				},
				client_id: messageManager.getClientId()
			};
			newsApi.friendsMessage(this, message).then((res) => {
				console.log('res-发送消息', res);
			})
			messageManager.sendMessage(message)

			this.content = ''
			this.scrollToBottom()
		},

		chooseImage() {
			uni.chooseImage({
				// sourceType: 'album',
				success: (res) => {
					this.list.push({
						content: res.tempFilePaths[0],
						userType: 'self',
						messageType: 'image',
						avatar: this._selfAvatar
					})
					this.scrollToBottom()
					// 模拟对方回复
					setTimeout(() => {
						this.list.push({
							content: '你好呀，朋友~',
							userType: 'friend',
							avatar: this._friendAvatar
						})
						this.scrollToBottom()
					}, 1500)
				}
			})
		},

		scrollToBottom() {
			// 使用 scroll-into-view 滚动到最新消息
			if (this.list.length > 0) {
				this.scrollIntoView = 'msg-' + (this.list.length - 1)
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.time-box {
	display: flex;
	justify-content: center;
	margin-bottom: 20rpx;
}

.time-text {
	font-size: 24rpx;
	color: #999;
	background-color: rgba(0, 0, 0, 0.1);
	padding: 4rpx 16rpx;
	border-radius: 20rpx;
}

.page {
	height: 100vh;
	background: #eee;
	position: relative;
}

.scroll-view {
	background: #eee;
	box-sizing: border-box;
	transition: height 0.3s ease;
}

.message {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 10rpx;
		margin-right: 30rpx;
	}

	.content {
		min-height: 70rpx;
		max-width: 60vw;
		box-sizing: border-box;
		font-size: 28rpx;
		line-height: 1.3;
		padding: 20rpx;
		border-radius: 10rpx;
		background: #fff;
		overflow-wrap: break-word;

		image {
			width: 200rpx;
		}
	}

	&.self {
		justify-content: flex-end;

		.avatar {
			margin: 0 0 0 30rpx;
		}

		.content {
			position: relative;

			&::after {
				position: absolute;
				content: '';
				width: 0;
				height: 0;
				border: 16rpx solid transparent;
				border-left: 16rpx solid #fff;
				right: -28rpx;
				top: 24rpx;
			}
		}
	}

	&.friend {
		.content {
			position: relative;

			&::after {
				position: absolute;
				content: '';
				width: 0;
				height: 0;
				border: 16rpx solid transparent;
				border-right: 16rpx solid #fff;
				left: -28rpx;
				top: 24rpx;
			}
		}
	}
}

.tool {
	position: fixed;
	width: 100%;
	min-height: 120rpx;
	left: 0;
	background: #fff;
	display: flex;
	align-items: center;
	box-sizing: border-box;
	padding: 20rpx 24rpx 20rpx 40rpx;
	padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)/2) !important;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom)/2) !important;
	transition: bottom 0.3s ease;
	z-index: 999;

	.input {
		background: #eee;
		border-radius: 10rpx;
		height: 70rpx;
		margin-right: 30rpx;
		flex: 1;
		padding: 0 20rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}

	.thumb {
		width: 64rpx;
	}
}
</style>
